import { Server } from "ws";
import WebSocket = require("ws")
import { SocketClient } from "../socketClient/SocketClient";

export class WebSocketServeMain {

    private webSocketServer: Server;
    private server: WebSocket;

    private callback: Function;

    constructor(_port: number, socketClient: SocketClient) {
        this.webSocketServer = new Server({ port: _port }, () => {
            console.log('webSocket_port:', _port);
        });
        this.webSocketServer.on('connection', (socket: WebSocket) => {
            console.log('webSockert-连接成功...');
            socketClient.connect();
            this.initMonitor(socket);
        })
    }

    private initMonitor(server: WebSocket) {
        this.server = server;
        server.binaryType = 'arraybuffer'
        server.on('message', this.onMsg.bind(this));
    }

    private onMsg(data: WebSocket.Data) {
        // console.log('webSockertServe-收到消息:', data);
        // this.onSend(data)
        this.callback && this.callback(data);
    }

    setRecriveCallBack(func: (data: ArrayBuffer) => void) {
        this.callback = func;
    }

    onSend(data) {
        this.server.send(data);
    }

}